package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Transactional
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * @param taskDto
     * @return 任务id
     */
    @Override
    public long addTask(TaskDto taskDto) {
        //处理数据
        Long id = IdWorker.getId();
        taskDto.setTaskId(id);
        //1.保存到数据库中
        boolean res = addTakToDB(taskDto);

        if (res) {
            //2.保存到redis中
            addTakToRedis(taskDto);
        }
        return id;
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {
        // 表更新
        TaskDto taskDto = updateDB(taskId, ScheduleConstants.CANCELLED);
        //redis更新
        if (taskDto != null) {
            updateRedis(taskDto);
        }
        return false;
    }

    /**
     * 取出任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public TaskDto popTask(Integer type, Integer priority) {
        String key = type + "_" + priority;
        String lRightPop = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (StringUtils.isNotEmpty(lRightPop)){
            TaskDto taskDto = JSON.parseObject(lRightPop, TaskDto.class);
            updateDB(taskDto.getTaskId(), ScheduleConstants.EXECUTED);
            return taskDto;
        }
        return null;
    }

    /**
     * 刷新zset
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void refreshRedis() {
        log.info("redis定时刷新");
        //查询zset中符合条件的数据
        Set<String> keyList = cacheService.scan(ScheduleConstants.FUTURE + "*");
        for (String key : keyList) {
            Set<String> task = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
            if (task != null && task.size() > 0) {
                cacheService.refreshWithPipeline(key, key.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC), task);
            }
        }
    }

    /**
     * 同步数据库任务到redis
     * 1.构造 --> TaskServiceImpl taskServiceImpl
     * 2.DI 依赖注入
     * 3.初始化 init()
     * 4.使用
     * 5.销毁 Destroyed()
     */
    @Override
    @PostConstruct // Bean的初始化方法，当bean被创建好，会自动调用一次
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshDBToRedis() {
        Set<String> futureKey = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKey = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKey);
        cacheService.delete(topicKey);
        long futureTime = System.currentTimeMillis() + (1000 * 60 * 5);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, new Date(futureTime)));
        for (Taskinfo taskinfo : taskinfos) {
            TaskDto taskDto = new TaskDto();
            BeanUtils.copyProperties(taskinfo, taskDto);
            taskDto.setExecuteTime(taskinfo.getExecuteTime().getTime());
            addTakToRedis(taskDto);
        }
    }

    /*更新redis*/
    private void updateRedis(TaskDto taskDto) {
        String key = taskDto.getTaskType() + "_" + taskDto.getPriority();
        if (taskDto.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(taskDto));
        } else {
            cacheService.zRemove(ScheduleConstants.TOPIC + key, JSON.toJSONString(taskDto));
        }
    }

    /*取消任务：更新表*/
    private TaskDto updateDB(Long taskId, int cancelled) {
        try {
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(cancelled);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            TaskDto taskDto = new TaskDto();
            BeanUtils.copyProperties(taskinfoLogs, taskDto);
            taskDto.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
            return taskDto;
        } catch (BeansException e) {
            return null;
        }
    }


    /*添加任务到redis*/
    private void addTakToRedis(TaskDto taskDto) {
        //key
        String key = taskDto.getTaskType() + "_" + taskDto.getPriority();
        //预留时间
        long timeout = System.currentTimeMillis() + (1000 * 60 * 5);

        if (taskDto.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(taskDto));
        } else if (taskDto.getExecuteTime() <= timeout) {
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(taskDto), taskDto.getExecuteTime());
        }
    }

    /*添加任务到数据库*/
    private boolean addTakToDB(TaskDto taskDto) {
        if (taskDto == null || taskDto.getParameters() == null) {
            return false;
        }
        try {
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(taskDto, taskinfo);
            taskinfo.setExecuteTime(new Date(taskDto.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            return true;
        } catch (BeansException e) {
            return false;
        }
    }
}
